package cn.tedu.product.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * 读取属性 自定义 easymall.es.nodes=ip:port,ip:port
 * TransportClient初始化方法 @Bean
 */
@Configuration
public class ESConfig {
    @Value("${easymall.es.nodes}")
    private List<String> nodes;
    //初始化方法
    @Bean
    public TransportClient initClient() throws UnknownHostException {
        //new一个client
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY);
        //解析 赋值
        for (String node: nodes
             ) {
            String host = node.split(":")[0];
            int port = Integer.parseInt(node.split(":")[1]);
            //创建address对象
            TransportAddress address = new InetSocketTransportAddress(InetAddress.getByName(host),port);
            client.addTransportAddress(address);
        }
        return client;
    }
}
